package org.primefaces.model.chart.flow.util;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.primefaces.json.JSONArray;
import org.primefaces.json.JSONException;
import org.primefaces.json.JSONObject;
import org.primefaces.model.chart.flow.FlowChartModel;
import org.primefaces.model.chart.flow.FlowDefaultAttributes;
import org.primefaces.model.chart.flow.FlowElementSet;
import org.primefaces.model.chart.flow.FlowHop;
import org.primefaces.model.chart.flow.FlowStep;
import org.primefaces.model.chart.flow.step.SysStepType;

/**
 * 用于生成Flow图形对象
 * 
 * @author 潘巍（Peter Pan）
 * @since 2011-2-11 下午06:00:06
 */
public class FlowGraphHelper {

	private final static Logger logger = Logger.getLogger(FlowElementSet.class
			.getName());

	/**
	 * 转换JSON对象为FlowChartModel对象
	 * 
	 * @param json
	 * @return
	 */
	public static FlowChartModel convertJsonToFlowChartModel(JSONObject json) {
		FlowChartModel co = null;
		try {
			if (json != null) {
				co = createFlowChartModel();
				co.construct(json);
				return co;
			}
		} catch (Exception e) {
			logger.log(Level.SEVERE,
					"Error in convert 'FlowChartModel' object from json.");
		}
		return null;
	}

	/**
	 * 创建流程图形模型(FlowChartModel)对象
	 * 
	 * @return
	 */
	public static FlowChartModel createFlowChartModel() {
		try {
			FlowChartModel co = new FlowChartModel();
			co.setElementSet(new FlowElementSet());
			co.setDefaultAttributes(new FlowDefaultAttributes());
			return co;
		} catch (Exception e) {
			logger
					.log(Level.SEVERE,
							"Error in create 'FlowChartModel' object.");
		}
		return null;
	}

	/**
	 * 创建线条(FlowHop)对象
	 * 
	 * @return
	 */
	public static FlowHop createHop() {
		return new FlowHop();
	}

	/**
	 * 创建图形(FlowStep)对象
	 * 
	 * @param st
	 * @return
	 */
	public static FlowStep createStep(String type) {
		try {
			if (type != null) {
				if (type.startsWith(FlowStep.SYS_FLOW_STEP_TYPE_PREFIX)) {
					return SysStepType.get(
							type.substring(FlowStep.SYS_FLOW_STEP_TYPE_PREFIX
									.length())).createStep();
				} else {
					Object obj = Class.forName(type).newInstance();
					if (obj instanceof FlowStep) {
						return (FlowStep) obj;
					}
				}
			}
		} catch (Exception e) {
			logger.log(Level.SEVERE, "Error in create 'FlowStep' object.");
		}
		return null;

	}

	public static final int[] convertJSONArrayToIntArray(JSONArray ja)
			throws JSONException {
		int n = ja.length();
		int[] rtn = new int[n];
		for (int i = 0; i < n; i++) {
			rtn[i] = ja.getInt(i);
		}
		return rtn;
	}

}
